/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;

/**
 *
 * @author Felipe
 */
public class UtilesImage
{
    /**
     * Convierte una imagen a un arreglo de bytes.
     * @param image la imagen a convertir
     * @param formato el formato de la imagen.
     * @return el arreglo representando la imagen, null si falla.
     * @throws java.io.IOException
     */
    public static byte[] imagenAByteArray (BufferedImage image, String formato) throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, formato, baos);
        baos.flush();
        byte[] bytes = baos.toByteArray();

        return bytes;
    }
    
    /**
     * Genera una imagen a partir de un arreglo de bytes.
     * @param image el arreglo que representa la imagen.
     * @return la imagen, null si falla.
     */
    public static BufferedImage ByteArrayAImage (byte[] image)
    {
        try
        {
            InputStream in = new ByteArrayInputStream(image);
            BufferedImage buffImage = ImageIO.read(in);
            
            return buffImage;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
    
    public static BufferedImage FileAImage (File file)
    {
        try
        {
            return ImageIO.read(file);
        }
        catch (Exception e)
        {
            return null;
        }
    }
    
    public static BufferedImage resize (BufferedImage image, int ancho, int alto)
    {
        return toBufferedImage(image.getScaledInstance(ancho, alto, Image.SCALE_SMOOTH));
    }
    
    /**
     * Converts a given Image into a BufferedImage
     *
     * @param img The Image to be converted
     * @return The converted BufferedImage
     */
    public static BufferedImage toBufferedImage(Image img)
    {
        if (img instanceof BufferedImage)
        {
            return (BufferedImage) img;
        }

        // Create a buffered image with transparency
        BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

        // Draw the image on to the buffered image
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(img, 0, 0, null);
        bGr.dispose();

        // Return the buffered image
        return bimage;
    }
}
